package com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.ydkj.a37e_mall.Classes.Applicatiom.MyApplication;
import com.ydkj.a37e_mall.Classes.Model.Request.MessageSystemReq;
import com.ydkj.a37e_mall.Classes.Model.Response.MessageSystemResp;
import com.ydkj.a37e_mall.R;
import com.ydkj.a37e_mall.Resource.Utils.Async_http_get;
import com.ydkj.a37e_mall.Resource.Utils.CommonUtil;
import com.ydkj.a37e_mall.Resource.Utils.Const;
import com.ydkj.a37e_mall.Resource.Utils.GsonImpl;
import com.ydkj.a37e_mall.Resource.Utils.SharedPreferencesUtil;
import com.ydkj.a37e_mall.Resource.View.CustomProgressDialog;
import com.ydkj.a37e_mall.Resource.View.StatusBarUtil;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by hong on 2016/3/16.
 * <p>
 * 系统消息
 */
public class MessageSystem extends Activity implements View.OnClickListener {
    private Activity mActivity;
    private SharedPreferencesUtil sharedPreferencesUtil;
    private MyApplication myApplication;
    private ImageView img_back;
    private TextView tv_edit, tv_delete, tv_no_message_data;
    private PullToRefreshListView plv_message;

    private String[] name = {"", "", "", "", "", ""};
    private List<MessageSystemResp.ResultEntity.DataEntity> dataEntityList;
    private MessageSystemAdapter messageSystemAdapter;
    private static final int LOAD = 0;// 加载
    private static final int REFRESH = 1;//刷新
    private static final int MORE = 2;// 更多
    private String secret;
    private int page;
    private boolean is_edit = false;

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.message_system);
        init();
        initWindow();
    }

    private void initWindow() {
        StatusBarUtil.setColor(mActivity, getResources().getColor(R.color.A000000), 0);

    }

    private void init() {
        mActivity = this;
        sharedPreferencesUtil = SharedPreferencesUtil.getInstance(mActivity);
        myApplication = MyApplication.getInstance();
        img_back = (ImageView) this.findViewById(R.id.img_back);
        tv_edit = (TextView) this.findViewById(R.id.tv_edit);
        plv_message = (PullToRefreshListView) mActivity.findViewById(R.id.plv_message);
        tv_delete = (TextView) mActivity.findViewById(R.id.tv_delete);
        tv_no_message_data = (TextView) mActivity.findViewById(R.id.tv_no_message_data);

        tv_delete.setVisibility(View.GONE);
        tv_edit.setVisibility(View.GONE);
        dataEntityList = new ArrayList<MessageSystemResp.ResultEntity.DataEntity>();
        messageSystemAdapter = new MessageSystemAdapter(dataEntityList);
        plv_message.setAdapter(messageSystemAdapter);

//        GetSytemMessage(REFRESH);
        plv_message.setOnRefreshListener2(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                GetSytemMessage(REFRESH);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                GetSytemMessage(MORE);
            }
        });
        img_back.setOnClickListener(this);
        tv_delete.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_back://返回
                finish();
                break;
            case R.id.tv_edit://编辑
                if (is_edit == false) {
                    tv_edit.setText("完成");
                    tv_delete.setVisibility(View.VISIBLE);
                    is_edit = true;
                } else {
                    tv_edit.setText("编辑");
                    tv_delete.setVisibility(View.GONE);
                    is_edit = false;
                }
                messageSystemAdapter.notifyDataSetChanged();
                break;
            case R.id.tv_delete://删除
                finish();
                break;
        }
    }

    private class MessageSystemAdapter extends BaseAdapter {
        private List<MessageSystemResp.ResultEntity.DataEntity> dataEntityList;
        Typeface type = Typeface.create("", Typeface.BOLD);

        private MessageSystemAdapter(List<MessageSystemResp.ResultEntity.DataEntity> dataEntities) {
            if (dataEntities == null) {
                dataEntities = new ArrayList<MessageSystemResp.ResultEntity.DataEntity>();
            }
            dataEntityList = dataEntities;
        }

        @Override
        public int getCount() {
            return dataEntityList.size();
        }

        /**
         * 获得某一位置的数据
         */
        @Override
        public MessageSystemResp.ResultEntity.DataEntity getItem(int position) {
            return dataEntityList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder vh = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(mActivity).inflate(R.layout.message_system_listitem, null);
                vh = new ViewHolder();
//                vh.img_choose = (ImageView) convertView.findViewById(R.id.img_choose);
                vh.cb_choose = (CheckBox) convertView.findViewById(R.id.cb_choose);
                vh.tv_title = (TextView) convertView.findViewById(R.id.tv_title);
                vh.tv_content = (TextView) convertView.findViewById(R.id.tv_content);
                vh.tv_time = (TextView) convertView.findViewById(R.id.tv_time);

            } else {
                vh = (ViewHolder) convertView.getTag();
            }
            convertView.setTag(vh);
            convertView.setClickable(true);

//            if (is_edit == true) {
//                vh.img_choose.setVisibility(View.VISIBLE);
//            } else {
            vh.cb_choose.setVisibility(View.GONE);
//            }

            if (getItem(position).getStatus() == 0) {//未读消息
                vh.tv_title.setTextColor(getResources().getColor(R.color.e50011));
            } else if (getItem(position).getStatus() == 1) {//已读消息
                vh.tv_title.setTextColor(getResources().getColor(R.color.A666666));
            }

            vh.tv_content.setText(getItem(position).getMessage());
            vh.tv_time.setText(getItem(position).getCreated_at());
            vh.tv_title.setText(getItem(position).getTitle());

            final ViewHolder finalVh = vh;
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int i = sharedPreferencesUtil.getPush();
                    sharedPreferencesUtil.setPush(i - 1);

                    if (i <= 0) {
                        sharedPreferencesUtil.setPush(0);
                    }
                    Log.e("url", "is_edit==22222");
                    Intent intent = new Intent(mActivity, MessageDetails.class);
                    intent.putExtra("id", getItem(position).getId());
                    intent.putExtra("desc", getItem(position).getMessage());
                    intent.putExtra("time", getItem(position).getCreated_at());
                    intent.putExtra("title", getItem(position).getTitle());
                    intent.putExtra("flag", "announces");
                    intent.putExtra("code", "1");
                    startActivityForResult(intent, 1);
                }
            });

            return convertView;
        }

        private class ViewHolder {
            private ImageView img_choose;
            private CheckBox cb_choose;
            private TextView tv_title;
            public TextView tv_content;
            public TextView tv_time;
        }
    }

    private void GetSytemMessage(final int type) {
        CustomProgressDialog.createDialog(mActivity).Show();
        MessageSystemReq req = new MessageSystemReq();

        if (myApplication.getDataEntity() == null) {
            return;
        } else {
            req.setUuid(myApplication.getDataEntity().getUuid());
        }

        if (myApplication.getMessage_time() == null) {
            req.setTime("1");
        } else {
            req.setTime(myApplication.getMessage_time());
        }

        if (type == LOAD || type == REFRESH) {
            page = 1;
        } else {
            page = dataEntityList.size() / 10 + 1;
        }
        req.setPage(page + "");
        req.setType("0");
        req.setPage_size("10");

        RequestParams params = new RequestParams();

        if (sharedPreferencesUtil.getAccessToken() != null) {
            params.put("token", sharedPreferencesUtil.getAccessToken());
        }

        params.put("secret", req.getSecret());

        Async_http_get.get(Const.COMMON_ADDRESS + req.urlString(), params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                Log.e("url", "system_meesage_json==" + response);
                CustomProgressDialog.Dismiss();
                plv_message.onRefreshComplete();
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");
                if (errno.equals("000")) {
                    MessageSystemResp resp = GsonImpl.get().toObject(response.toString(), MessageSystemResp.class);
                    myApplication.setMessage_time(System.currentTimeMillis() + "");
                    if (type == LOAD || type == REFRESH) {
                        dataEntityList.clear();
                        dataEntityList.addAll(resp.getResult().getData());
                    } else {
                        dataEntityList.addAll(resp.getResult().getData());
                    }
                    if (dataEntityList.size() % 10 > 0) {
                        plv_message.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                    } else {
                        plv_message.setMode(PullToRefreshBase.Mode.BOTH);
                    }
                    messageSystemAdapter.notifyDataSetChanged();
                    plv_message.onRefreshComplete();
                } else if (errno.equals("999")) {
                    CommonUtil.showToast(mActivity, errmsg);
                    Intent intent = new Intent(mActivity, LoginActivity.class);
                    startActivityForResult(intent, 1);
                    Log.e("url", "errmsg==" + errmsg);
                } else {
                    tv_no_message_data.setVisibility(View.VISIBLE);
                    CommonUtil.showToast(mActivity, errmsg);
                    messageSystemAdapter.notifyDataSetChanged();
                    plv_message.onRefreshComplete();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                CustomProgressDialog.Dismiss();
                CommonUtil.showToast(mActivity, "网络连接失败");
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e("url", "messageVip_onResume");
        GetSytemMessage(REFRESH);
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e("url", "messageVip_onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.e("url", "messageVip_onStop");
    }


}
